package com.example.lenovo.asia5b.util;

import com.example.lenovo.asia5b.commodity.bean.ClassifyBean;
import com.example.lenovo.asia5b.commodity.bean.ClassifyThreeBean;
import com.example.lenovo.asia5b.commodity.bean.ClassifyTwoBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Created by lenovo on 2017/7/4.
 */

public class Logic {

    /**
     * 根据JSON，传入bean封装数据后返回Object,
     * 调用方法时，需要new一个bean,接收返回的参数需要强转
     * @param jsonObject
     * @param bean
     */
    public static Object getBeanToJSONObject(JSONObject jsonObject, Object bean) throws Exception {
        return analyzeObject(jsonObject,bean);
    }

    private static Object analyzeObject(JSONObject jsonObject, Object bean) throws Exception {
        Class beanClass = Class.forName(bean.getClass().getName());
        Object objBean = beanClass.newInstance();
        Iterator<String> iter = jsonObject.keys();
        List<String> keyList = new ArrayList<>();
        Field field = null;
        while(iter.hasNext()){
            String keyStr = iter.next();
            try {
                field = objBean.getClass().getDeclaredField(keyStr);
            }catch (Exception e) {
                continue;
            }
            field.setAccessible(true);
            String jsonValue = jsonObject.getString(keyStr);
            field.set(objBean,jsonValue);
        }
        return objBean;
    }

    /**
     * 根据JSON数组返回List
     * @param array
     * @param bean
     * @return
     * @throws Exception
     */
    public static List getListToBean(JSONArray array, Object bean) throws Exception {
        return jsonToList(array,bean);
    }

    private static List jsonToList(JSONArray array, Object bean) throws Exception {
        Class beanClass = Class.forName(bean.getClass().getName());
        List list = new ArrayList();
        for (int i = 0; i < array.length(); i++) {
            JSONObject json = array.getJSONObject(i);
            Object objBean = beanClass.newInstance();
            Field field = null;
            Iterator<String> iter = json.keys();
            List<String> keyList = new ArrayList<>();
            while(iter.hasNext()){
                String keyStr = iter.next();
                try {
                    field = objBean.getClass().getDeclaredField(keyStr);
                }catch (Exception e) {
                    continue;
                }
                field.setAccessible(true);
                if(List.class.isAssignableFrom(field.getType())){
                    List arraylist = new ArrayList();
                    JSONArray jsonArray = json.optJSONArray(keyStr);
                    getListToBeanNext(jsonArray,arraylist,beanClass);
                    field.set(objBean,arraylist);
                }else{
                    String jsonValue = json.optString(keyStr);
                    field.set(objBean,jsonValue);
                }
            }
            list.add(objBean);
        }
        return list;
    }

    private static void getListToBeanNext(JSONArray array, List listNext,Class beanClass) throws Exception{
        for (int i = 0; i < array.length(); i++) {
            JSONObject json = array.getJSONObject(i);
            Iterator<String> iter = json.keys();
            List<String> keyList = new ArrayList<>();
            while(iter.hasNext()){
                keyList.add(iter.next());
            }
            Object objBean = beanClass.newInstance();
            for (int k = 0; k < keyList.size(); k++){
                String key = keyList.get(k);
                Field field = objBean.getClass().getDeclaredField(key);
                String type = field.getType().getName();
                String fieldName = field.getName();
                String jsonValue = null;
                if(List.class.isAssignableFrom(field.getType())){
                    List arraylist = new ArrayList();
                    JSONArray jsonArray = json.getJSONArray(key);
                    getListToBeanNext(jsonArray,arraylist,beanClass);
                    field.set(objBean,arraylist);
                }else{
                    jsonValue = json.optString(key);
                    field.set(objBean,jsonValue);
                }
            }
            listNext.add(objBean);
        }
    }

    /**
     * 根据英文首字母排序
     * @param arrayToSort
     * @return
     */
    public static String sortToString(String[] arrayToSort) {
        List<String> list = new ArrayList<>();
        // 调用数组的静态排序方法sort,且不区分大小写
        Arrays.sort(arrayToSort,String.CASE_INSENSITIVE_ORDER);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arrayToSort.length; i++){
            sb.append(arrayToSort[i]);
        }
        sb.append(Setting.SECRETKEY);
        return sb.toString();
    }

    public static List<ClassifyBean> getCalssifyList(JSONArray jsonArray) throws JSONException {
        List<ClassifyBean> lists = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            ClassifyBean oneBean = new ClassifyBean();
            oneBean.setCat_id(json.optString("cat_id"));
            oneBean.setCat_name(json.optString("cat_name"));
            oneBean.setFileico(json.optString("fileico"));

            List<ClassifyTwoBean> twoLists = new ArrayList<>();
            List<ClassifyThreeBean> threeLists = new ArrayList<>();

            JSONArray twoArray = json.optJSONArray("childs");
            for (int j = 0; j < twoArray.length(); j++) {
                ClassifyTwoBean twoBean = new ClassifyTwoBean();
                JSONObject twoJson = twoArray.optJSONObject(j);
                twoBean.setCat_id(twoJson.optString("cat_id"));
                twoBean.setCat_name(twoJson.optString("cat_name"));
                twoBean.setFileico(twoJson.optString("fileico"));
                twoBean.setParent_id(twoJson.optString("parent_id"));
                twoLists.add(twoBean);

                JSONArray threeArray = twoJson.optJSONArray("childs");
                if (threeArray != null){
                    for (int k = 0; k < threeArray.length(); k++) {
                        ClassifyThreeBean threeBean = new ClassifyThreeBean();
                        JSONObject threeJson = threeArray.optJSONObject(k);
                        if (threeJson != null){
                            threeBean.setCat_id(threeJson.optString("cat_id"));
                            threeBean.setCat_name(threeJson.optString("cat_name"));
                            threeBean.setFileico(threeJson.optString("fileico"));
                            threeBean.setParent_id(threeJson.optString("parent_id"));
                            threeLists.add(threeBean);
                        }
                    }
                }
            }
            oneBean.setChilds(twoLists);
            oneBean.setThreeChilds(threeLists);
            lists.add(oneBean);
        }
        return lists;
    }
}